package com.ankiang.treeprint.fragment.home;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ankiang.treeprint.QDMainActivity;
import com.ankiang.treeprint.R;
import com.ankiang.treeprint.base.BaseFragment;
import com.ankiang.treeprint.base.BaseRecyclerAdapter;
import com.ankiang.treeprint.decorator.GridDividerItemDecoration;
import com.ankiang.treeprint.fragment.components.TRAddGroupFragment;
import com.ankiang.treeprint.fragment.components.TRHelpFragment;
import com.ankiang.treeprint.fragment.components.TRHomeTreeFragment;
import com.ankiang.treeprint.fragment.components.TRShowTextFragment;
import com.ankiang.treeprint.fragment.util.QDNotchHelperFragment;
import com.ankiang.treeprint.fragment.util.TRPages;
import com.ankiang.treeprint.fragment.util.TRUtils;
import com.ankiang.treeprint.lib.TRDataManager;
import com.ankiang.treeprint.manager.QDDataManager;
import com.ankiang.treeprint.model.LOG;
import com.ankiang.treeprint.model.TRGroupItem;
import com.ankiang.treeprint.model.TRGroupList;
import com.ankiang.treeprint.model.TRItemTree;
import com.qmuiteam.qmui.alpha.QMUIAlphaImageButton;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.grouplist.QMUIGroupListView;
import com.qmuiteam.qmui.widget.popup.QMUIListPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import com.qmuiteam.qmui.widget.pullRefreshLayout.QMUIPullRefreshLayout;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;

/**
 * @author cginechen
 * @date 2016-10-20
 */

public class HomeHomeController extends HomeController {

    static final String TAG = "HomeHomeController";

    // 分组
    private TRGroupList mGroupList;


    @BindView(R.id.pull_to_refresh)
    QMUIPullRefreshLayout mPullRefreshLayout;

    @BindView(R.id.trGroupListView)
    ListView mTrGroupListView;

    @BindView(R.id.groupListView)
    QMUIGroupListView mGroupListView;

    @BindView(R.id.orderImageButton)
    ImageButton mOrderImageButton;


    static final int ORDER_TYPE_TIME = 0;
    static final int ORDER_TYPE_ALPHA = 1;
    int mOrderType = 0;

    // 广告条
    TRBanner banner;

    TRDataManager dataManager;


    // 右上角列表
    private QMUIListPopup mListPopup;
    private QMUIAlphaImageButton mRightButton;


    private QMUIListPopup mGroupListPopup;

    public HomeHomeController(Context context) {
        super(context, R.layout.home_home_layout);

        dataManager = TRDataManager.getInstance(context);
        dataManager.load();

        // todo add demo data


        initWithGroupList();
        initRecyclerView();
        initListener();
        banner = new TRBanner();
        banner.initBanner(this);


    }

    private void initListener() {
        mOrderImageButton.setOnClickListener(v -> {
            mOrderType = (mOrderType + 1) % 2; // 只有两种排序方法
            initWithGroupList();
        });

        mPullRefreshLayout.setOnPullListener(new QMUIPullRefreshLayout.OnPullListener() {
            @Override
            public void onMoveTarget(int offset) {

            }

            @Override
            public void onMoveRefreshView(int offset) {

            }

            @Override
            public void onRefresh() {
                initWithGroupList();
                mPullRefreshLayout.finishRefresh();
//                mPullRefreshLayout.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        mPullRefreshLayout.finishRefresh();
//                    }
//                }, 2000);
            }
        });
    }

    private void initWithGroupList() {


//        mTrGroupListView.removeAllViews();

//        QMUIGroupListView.Section section = QMUIGroupListView.newSection(getContext());

        try {
            JSONObject jGroup = dataManager.getGroupList();
            mGroupList = TRGroupList.convert(jGroup);
            JSONArray list = mGroupList.toArray();
            final List<TRGroupItem> gList = new ArrayList();


            for (int i = 0; i < list.size(); i++) {
                JSONObject groupObj = list.getJSONObject(i);
                TRGroupItem groupItem = TRGroupItem.convert(groupObj);

                if (groupItem.getName() == null) {
                    groupItem.setName("未命名");
                }
                if (groupItem.getId() == 0) {
                    continue; // 不将示例数据放在这里
                }
                if (groupItem.getId() == -1) {
                    continue; // 不将大家族的数据放在这里
                }
                gList.add(groupItem);
            }


            if (mOrderType == ORDER_TYPE_ALPHA) {
                mOrderImageButton.setImageResource(R.drawable.ic_order_alpha);
                Collections.sort(gList, (o1, o2) -> {
                    if (o1 == null || o1.getName() == null) {
                        return 1;
                    }

                    if (o2 == null || o2.getName() == null) {
                        return -1;
                    }

                    Collator collator = Collator.getInstance(Locale.CHINA);
                    return collator.getCollationKey(o1.getName())
                            .compareTo(collator.getCollationKey(o2.getName()));

                });
            } else {
                mOrderImageButton.setImageResource(R.drawable.ic_order_time);
                Collections.sort(gList, (o2, o1) -> {
                    if (o1 == null || o1.getUpdatetime() == null) {
                        return 1;
                    }

                    if (o2 == null || o2.getUpdatetime() == null) {
                        return -1;
                    }

                    Collator collator = Collator.getInstance(Locale.CHINA);
                    return collator.getCollationKey(o1.getUpdatetime())
                            .compareTo(collator.getCollationKey(o2.getUpdatetime()));
                });
            }

            mTrGroupListView.setAdapter(new BaseAdapter() {
                @Override
                public int getCount() {
                    return gList.size();//数目
                }

                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                    LayoutInflater inflater = LayoutInflater.from(getContext());
                    View view;
                    if (convertView == null) {
                        //因为getView()返回的对象，adapter会自动赋给ListView
                        view = inflater.inflate(R.layout.home_home_group_item_layout, null);
                    } else {
                        view = convertView;
                        //Log.i("info", "有缓存，不需要重新生成" + position);
                    }


                    TRGroupItem item = gList.get(position);
                    view.setTag(item.getId());


                    Drawable imgDrawable = null;
                    String imgPath = item.getImage();

                    if(null != imgPath && !imgPath.equals("")) {
                        imgDrawable = Drawable.createFromPath(imgPath);
                    }
                    if(imgDrawable == null){ // 如果上一部没有创建成功，也会调用这里
                        imgDrawable = getResources().getDrawable(R.drawable.group_image);
                    }

                    ImageView image = view.findViewById(R.id.group_image);//.setImageResource(item.getIconRes());
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        image.setImageDrawable(imgDrawable);
                    }

                    TextView tv1 = (TextView) view.findViewById(R.id.group_name);//找到Textviewname
                    tv1.setText(item.getName());//设置参数

                    TextView tv2 = (TextView) view.findViewById(R.id.group_note);//找到Textviewage
                    tv2.setText(item.getNote());//设置参数
                    view.setTag(item.getId());


                    return view;
                }

                @Override
                public long getItemId(int position) {//取在列表中与指定索引对应的行id
                    return position;
                }

                @Override
                public Object getItem(int position) {//获取数据集中与指定索引对应的数据项

                    TRGroupItem item = gList.get(position);

                    return item;
                }

            });

            TRUtils.setListViewHeightBasedOnChildren(mTrGroupListView);


            AdapterView.OnItemClickListener onClickGroupItemListener = new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    int group = (int) view.getTag();
//                    showHomeTreePage(group);
                    TRHomeTreeFragment fragment = new TRHomeTreeFragment();
                    fragment.setGroup(group);
                    fragment.setCallback(o -> {
                        initWithGroupList();
                    });

                    startFragment(fragment);
                }
            };

            mTrGroupListView.setOnItemClickListener(onClickGroupItemListener);
            mTrGroupListView.setOnLongClickListener(new OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    showGroupOperations(v);
                    return false;
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
            LOG.jLoge(TAG, e.getMessage());
        }

    }


    @Override
    void initTopBar() {
        mTopBar.setTitle(getTitle());

        mRightButton = mTopBar.addRightImageButton(R.mipmap.icon_topbar_overflow, R.id.topbar_right_change_button);
        mRightButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showBottomSheet();
            }
        });
    }


    @Override
    void initRecyclerView() {
        mItemAdapter = getItemAdapter();
        if (mItemAdapter == null) {
            return;
        }
        mItemAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, int pos) {
                QDDataManager.QDItemDescription item = mItemAdapter.getItem(pos);
                try {
                    BaseFragment fragment = item.getDemoClass().newInstance();
                    if (fragment instanceof QDNotchHelperFragment) {
                        Context context = getContext();
                        Intent intent = QDMainActivity.createNotchHelperIntent(context);
                        context.startActivity(intent);
                        if (context instanceof Activity) {
                            ((Activity) context).overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
                        }
                    } else if (fragment instanceof TRHelpFragment) {
                        TRPages.showHelpPage(HomeHomeController.this);
                    } else {
                        startFragment(fragment);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        mRecyclerView.setAdapter(mItemAdapter);
        int spanCount = 4;
        mRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), spanCount));
        mRecyclerView.addItemDecoration(new GridDividerItemDecoration(getContext(), spanCount));
    }


    @Override
    protected ItemAdapter getItemAdapter() {
        return new ItemAdapter(getContext(), QDDataManager.getInstance(getContext()).getHomeDescriptions());
    }

    // --------------------------------------------------
    // 操作
    private void showBottomSheet() {

        View v = mRightButton;
        initListPopupIfNeed();
        mListPopup.setAnimStyle(QMUIPopup.ANIM_GROW_FROM_CENTER);
        mListPopup.setPreferredDirection(QMUIPopup.DIRECTION_TOP);
        mListPopup.show(v);

    }


    private void initListPopupIfNeed() {
        if (mListPopup == null) {

            String[] listItems = new String[]{
                    V(R.string.tree_op_add_group),
                    V(R.string.show_text)
            };
            List<String> data = new ArrayList<>();

            Collections.addAll(data, listItems);

            ArrayAdapter adapter = new ArrayAdapter<>(getContext(), R.layout.simple_list_item, data);

            mListPopup = new QMUIListPopup(getContext(), QMUIPopup.DIRECTION_NONE, adapter);
            mListPopup.create(QMUIDisplayHelper.dp2px(getContext(), 120), QMUIDisplayHelper.dp2px(getContext(), 200), new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    //Toast.makeText(getContext(), "Item " + (i + 1), Toast.LENGTH_SHORT).show();

                    switch (i) {
                        case 0:
                            showAddGroupPage();
                            break;
                        case 1:
                            showTextPage();
                            break;
                        default:
                            break;
                    }
                    mListPopup.dismiss();
                }
            });
            mListPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
//                    mActionButton2.setText(getContext().getResources().getString(R.string.popup_list_action_button_text_show));
                }
            });
        }
    }

    private void showTextPage() {
        TRShowTextFragment fragment = new TRShowTextFragment();
        fragment.setOp(TRShowTextFragment.OP_SHOW_GROUP_LIST);
        startFragment(fragment);
    }


    // --------------------------------------------------
    // 操作分组
    private void showGroupOperations(View v) {
        int id = (int) v.getTag();
        initGroupListPopupIfNeed();
        mGroupListPopup.setAnimStyle(QMUIPopup.ANIM_GROW_FROM_CENTER);
        mGroupListPopup.setPreferredDirection(QMUIPopup.DIRECTION_TOP);
        mGroupListPopup.show(v);

    }


    private void initGroupListPopupIfNeed() {
        if (mListPopup == null) {

            String[] listItems = new String[]{
                    V(R.string.tree_op_add_group)
            };
            List<String> data = new ArrayList<>();

            Collections.addAll(data, listItems);

            ArrayAdapter adapter = new ArrayAdapter<>(getContext(), R.layout.simple_list_item, data);

            mListPopup = new QMUIListPopup(getContext(), QMUIPopup.DIRECTION_NONE, adapter);
            mListPopup.create(QMUIDisplayHelper.dp2px(getContext(), 120), QMUIDisplayHelper.dp2px(getContext(), 200), new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    //Toast.makeText(getContext(), "Item " + (i + 1), Toast.LENGTH_SHORT).show();

                    switch (i) {
                        case 0:
                            showAddGroupPage();
                            break;
                        default:
                            break;
                    }
                    mListPopup.dismiss();
                }
            });
            mListPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                }
            });
        }
    }


    @Override
    protected String getTitle() {
        return V(R.string.app_name);
    }


    /**
     * 显示新增节点页面
     */
    private void showAddGroupPage() {
        TRAddGroupFragment fragment = new TRAddGroupFragment();
        fragment.setOp(TRAddGroupFragment.ADD);

        Bundle bundle = new Bundle();
        TRGroupItem data = new TRGroupItem();
        data.setId(dataManager.getNextGroupId());
        int tag = TRAddGroupFragment.ADD;
        bundle.putInt(TRAddGroupFragment.KEY_TAG, tag);
        bundle.putSerializable(TRAddGroupFragment.KEY_DATA, data);
        fragment.setArguments(bundle);

        fragment.setAfterOperation(id -> {
            initWithGroupList();
        });
        startFragment(fragment);

    }


}
